<template>
  <div class="min-h-screen bg-gray-900">
    <!-- 播放器容器 -->
    <div class="relative">
      <video
        ref="videoPlayer"
        class="w-full h-screen bg-black"
        controls
        @loadedmetadata="onLoadedMetadata"
        @timeupdate="onTimeUpdate"
        @ended="onEnded"
        @error="onError"
      >
        <source v-if="currentMedia?.url" :src="currentMedia.url" />
        <track
          v-for="subtitle in currentMedia?.subtitles"
          :key="subtitle.url"
          :src="subtitle.url"
          :label="subtitle.label"
          :srclang="subtitle.language"
          kind="subtitles"
        />
      </video>

      <!-- 自定义控制栏 -->
      <div
        v-if="showControls"
        class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4"
      >
        <!-- 进度条 -->
        <div class="mb-4">
          <input
            v-model="progress"
            type="range"
            min="0"
            max="100"
            class="w-full h-1 bg-gray-600 rounded-lg appearance-none cursor-pointer"
            @input="seekTo"
          />
          <div class="flex justify-between text-xs text-gray-300 mt-1">
            <span>{{ formatTime(currentTime) }}</span>
            <span>{{ formatTime(duration) }}</span>
          </div>
        </div>

        <!-- 控制按钮 -->
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <button @click="togglePlay" class="text-white hover:text-gray-300">
              <i :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'" class="text-xl"></i>
            </button>
            
            <div class="flex items-center space-x-2">
              <button @click="toggleMute" class="text-white hover:text-gray-300">
                <i :class="volume === 0 ? 'fas fa-volume-mute' : 'fas fa-volume-up'"></i>
              </button>
              <input
                v-model="volume"
                type="range"
                min="0"
                max="1"
                step="0.1"
                class="w-20 h-1 bg-gray-600 rounded-lg appearance-none cursor-pointer"
                @input="setVolume"
              />
            </div>

            <button @click="toggleFullscreen" class="text-white hover:text-gray-300">
              <i class="fas fa-expand"></i>
            </button>
          </div>

          <div class="flex items-center space-x-4">
            <!-- 画质选择 -->
            <select
              v-model="quality"
              @change="changeQuality"
              class="bg-gray-800 text-white px-2 py-1 rounded text-sm"
            >
              <option v-for="q in availableQualities" :key="q" :value="q">
                {{ q }}
              </option>
            </select>

            <!-- 音效选择 -->
            <select
              v-model="audioEffect"
              @change="changeAudioEffect"
              class="bg-gray-800 text-white px-2 py-1 rounded text-sm"
            >
              <option v-for="effect in audioEffects" :key="effect.id" :value="effect.id">
                {{ effect.name }}
              </option>
            </select>

            <!-- 下载按钮 -->
            <button @click="download" class="text-white hover:text-gray-300">
              <i class="fas fa-download"></i>
            </button>

            <!-- 设置按钮 -->
            <button @click="showSettings = !showSettings" class="text-white hover:text-gray-300">
              <i class="fas fa-cog"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 侧边设置面板 -->
    <div
      v-if="showSettings"
      class="fixed right-0 top-0 h-full w-80 bg-gray-800 shadow-lg p-4 overflow-y-auto"
    >
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold text-white">设置</h3>
        <button @click="showSettings = false" class="text-gray-400 hover:text-white">
          <i class="fas fa-times"></i>
        </button>
      </div>

      <!-- 滤镜设置 -->
      <div class="mb-6">
        <h4 class="text-white font-medium mb-3">视频滤镜</h4>
        <div class="space-y-2">
          <label class="flex items-center justify-between">
            <span class="text-sm text-gray-300">亮度</span>
            <input
              v-model="filters.brightness"
              type="range"
              min="0"
              max="200"
              class="w-32"
              @input="applyFilters"
            />
          </label>
          <label class="flex items-center justify-between">
            <span class="text-sm text-gray-300">对比度</span>
            <input
              v-model="filters.contrast"
              type="range"
              min="0"
              max="200"
              class="w-32"
              @input="applyFilters"
            />
          </label>
          <label class="flex items-center justify-between">
            <span class="text-sm text-gray-300">饱和度</span>
            <input
              v-model="filters.saturation"
              type="range"
              min="0"
              max="200"
              class="w-32"
              @input="applyFilters"
            />
          </label>
          <label class="flex items-center justify-between">
            <span class="text-sm text-gray-300">色相</span>
            <input
              v-model="filters.hue"
              type="range"
              min="0"
              max="360"
              class="w-32"
              @input="applyFilters"
            />
          </label>
        </div>
      </div>

      <!-- 音效设置 -->
      <div class="mb-6">
        <h4 class="text-white font-medium mb-3">音效增强</h4>
        <div class="space-y-2">
          <button
            v-for="effect in audioEffects"
            :key="effect.id"
            @click="selectAudioEffect(effect)"
            class="w-full text-left px-3 py-2 rounded text-sm"
            :class="audioEffect === effect.id ? 'bg-primary-600 text-white' : 'bg-gray-700 text-gray-300 hover:bg-gray-600'"
          >
            <div class="font-medium">{{ effect.name }}</div>
            <div class="text-xs opacity-75">{{ effect.description }}</div>
          </button>
        </div>
      </div>

      <!-- 播放速度 -->
      <div class="mb-6">
        <h4 class="text-white font-medium mb-3">播放速度</h4>
        <div class="flex items-center space-x-2">
          <button
            v-for="rate in [0.5, 0.75, 1, 1.25, 1.5, 2]"
            :key="rate"
            @click="setPlaybackRate(rate)"
            class="px-3 py-1 rounded text-sm"
            :class="playbackRate === rate ? 'bg-primary-600 text-white' : 'bg-gray-700 text-gray-300 hover:bg-gray-600'"
          >
            {{ rate }}x
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="fixed inset-0 bg-black/50 flex items-center justify-center">
      <div class="text-white">
        <i class="fas fa-spinner fa-spin text-2xl"></i>
        <div class="mt-2">加载中...</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useMediaStore } from '../stores/media'
import type { AudioEffect } from '../types/media'

const route = useRoute()
const mediaStore = useMediaStore()

// Refs
const videoPlayer = ref<HTMLVideoElement>()
const showControls = ref(true)
const showSettings = ref(false)
const loading = ref(false)

// 状态
const filters = ref({
  brightness: 100,
  contrast: 100,
  saturation: 100,
  hue: 0,
})

// 计算属性
const currentMedia = computed(() => mediaStore.currentMedia)
const isPlaying = computed(() => mediaStore.isPlaying)
const currentTime = computed(() => mediaStore.currentTime)
const duration = computed(() => mediaStore.duration)
const volume = computed({
  get: () => mediaStore.volume,
  set: (v) => mediaStore.volume = v,
})
const quality = computed({
  get: () => mediaStore.quality,
  set: (q) => mediaStore.quality = q,
})
const audioEffect = computed({
  get: () => mediaStore.audioEffect,
  set: (e) => mediaStore.audioEffect = e,
})
const playbackRate = computed({
  get: () => mediaStore.playbackRate,
  set: (r) => mediaStore.playbackRate = r,
})

const progress = computed({
  get: () => mediaStore.progress,
  set: (p) => seekTo(p),
})

const availableQualities = ref(['auto', '1080p', '720p', '480p', '360p'])
const audioEffects: AudioEffect[] = [
  { id: 'normal', name: '标准', description: '原始音效' },
  { id: 'viper', name: '蝰蛇音效', description: '增强低频和高频' },
  { id: '3d', name: '3D丽音', description: '立体声环绕效果' },
  { id: 'surround', name: '5.1全景', description: '5.1声道模拟' },
  { id: 'car', name: '汽车音效', description: '优化车载音响' },
  { id: 'concert', name: '演唱会', description: '现场感增强' },
  { id: 'hifi', name: 'HiFi', description: '高保真音质' },
]

// 方法
const togglePlay = () => {
  if (!videoPlayer.value) return
  
  if (isPlaying.value) {
    videoPlayer.value.pause()
  } else {
    videoPlayer.value.play()
  }
  mediaStore.isPlaying = !isPlaying.value
}

const toggleMute = () => {
  if (!videoPlayer.value) return
  videoPlayer.value.muted = !videoPlayer.value.muted
}

const setVolume = () => {
  if (!videoPlayer.value) return
  videoPlayer.value.volume = volume.value
}

const seekTo = (percentage: number) => {
  if (!videoPlayer.value) return
  const time = (percentage / 100) * duration.value
  videoPlayer.value.currentTime = time
}

const changeQuality = () => {
  // 实现画质切换逻辑
  console.log('切换画质:', quality.value)
}

const changeAudioEffect = () => {
  // 实现音效切换逻辑
  console.log('切换音效:', audioEffect.value)
}

const setPlaybackRate = (rate: number) => {
  if (!videoPlayer.value) return
  videoPlayer.value.playbackRate = rate
  mediaStore.playbackRate = rate
}

const selectAudioEffect = (effect: AudioEffect) => {
  audioEffect.value = effect.id
}

const applyFilters = () => {
  if (!videoPlayer.value) return
  
  const { brightness, contrast, saturation, hue } = filters.value
  videoPlayer.value.style.filter = `
    brightness(${brightness}%) 
    contrast(${contrast}%) 
    saturate(${saturation}%) 
    hue-rotate(${hue}deg)
  `
}

const toggleFullscreen = () => {
  if (!videoPlayer.value) return
  
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    videoPlayer.value.requestFullscreen()
  }
}

const download = () => {
  if (!currentMedia.value) return
  
  const a = document.createElement('a')
  a.href = currentMedia.value.url
  a.download = currentMedia.value.title
  a.click()
}

const onLoadedMetadata = () => {
  if (!videoPlayer.value) return
  mediaStore.duration = videoPlayer.value.duration
}

const onTimeUpdate = () => {
  if (!videoPlayer.value) return
  mediaStore.currentTime = videoPlayer.value.currentTime
  mediaStore.updatePlaybackHistory(currentMedia.value?.id || '', videoPlayer.value.currentTime)
}

const onEnded = () => {
  mediaStore.isPlaying = false
}

const onError = (e: Event) => {
  console.error('视频播放错误:', e)
}

const formatTime = (seconds: number): string => {
  if (!seconds || seconds === 0) return '00:00'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 鼠标移动显示控制栏
let controlsTimeout: number
const handleMouseMove = () => {
  showControls.value = true
  clearTimeout(controlsTimeout)
  controlsTimeout = setTimeout(() => {
    if (isPlaying.value) {
      showControls.value = false
    }
  }, 3000)
}

// 监听键盘事件
const handleKeyPress = (e: KeyboardEvent) => {
  if (!videoPlayer.value) return
  
  switch (e.code) {
    case 'Space':
      e.preventDefault()
      togglePlay()
      break
    case 'ArrowLeft':
      e.preventDefault()
      videoPlayer.value.currentTime -= 10
      break
    case 'ArrowRight':
      e.preventDefault()
      videoPlayer.value.currentTime += 10
      break
    case 'ArrowUp':
      e.preventDefault()
      volume.value = Math.min(1, volume.value + 0.1)
      setVolume()
      break
    case 'ArrowDown':
      e.preventDefault()
      volume.value = Math.max(0, volume.value - 0.1)
      setVolume()
      break
  }
}

onMounted(() => {
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('keydown', handleKeyPress)
  
  if (videoPlayer.value) {
    videoPlayer.value.volume = volume.value
    videoPlayer.value.playbackRate = playbackRate.value
  }
})

onUnmounted(() => {
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('keydown', handleKeyPress)
  clearTimeout(controlsTimeout)
})

// 自动播放
watch(currentMedia, (newMedia) => {
  if (newMedia && videoPlayer.value) {
    loading.value = true
    videoPlayer.value.addEventListener('loadeddata', () => {
      loading.value = false
      videoPlayer.value?.play()
      mediaStore.isPlaying = true
    })
  }
})
</script>
